<?php
/**
 * Created by PhpStorm.
 * User: Liujianlin
 * Date: 2017/7/22
 * Time: 11:25
 */

namespace app\controllers\marketing;

use yii;
use app\base\Controller;
use app\components\redis\RedisMarketingEmail;
use app\models\marketing\RedisLog;

class RedisController extends Controller
{
    public $enableCsrfValidation = false;

    /**
     * redis缓存管理
     * @return string
     */
    public function actionIndex()
    {
        $method = yii::$app->request->getMethod();
        $redisKey = yii::$app->request->$method('key');

        $data = $this->getContent($redisKey);
        return $this->render("/marketing/redis/index", ['data' => $data, 'key' => $redisKey]);
    }

    /**
     * 获取redis key对应的内容
     * @param $redisKey
     * @return array|mixed
     */
    public function getContent($redisKey)
    {
        $cmdArr = [
            "zset" => ["zrange", $redisKey, 0, -1, "WITHSCORES"],
            "set" => ["SMEMBERS", $redisKey],
            "list" => ["lrange", $redisKey, 0, -1],
            "hash" => ["hgetall", $redisKey],
            'string' => ['get',$redisKey],
        ];
       
        $redis = new RedisMarketingEmail();
        $type = $redis->executeCommand('type', [$redisKey]);
        if (empty($type) || !key_exists($type, $cmdArr)) {
            return [];
        }

        // 执行查询命令
        $cmd = $cmdArr[$type];
        $realCmd = array_shift($cmd);
        $args = $cmd;
        $content = $redis->executeCommand($realCmd, $args);
        if (in_array($type, ["hash", "zset"])) {
            $data = $redis->redisArrToCommonArr($content);
        } else {
            $data = $content;
        }
        return $data;
    }

    /**
     * 删除redis key
     */
    public function actionDel()
    {
        $redis = new RedisMarketingEmail();
        $redisLogModel = new RedisLog();
        $method = yii::$app->request->getMethod();
        $redisKey = yii::$app->request->$method('key');
        if (empty($redisKey) || !$redis->executeCommand("exists", [$redisKey])) {
            $this->returnJson(10008, "不存在该key");
        }

        $type = $redis->executeCommand('type', [$redisKey]);
        $detail = $redis->executeCommand('del', [$redisKey]);
        $redisLogModel->writeLog('删除', $type, $redisKey, $detail ? '删除成功' : '删除失败');

        if ($detail >= 1) {
            $this->returnJson(0, "删除成功");
        } else {
            $this->returnJson(10009, "删除失败");
        }
    }
}